<template>
	<my-page title="收藏记录" :is-back="true" :is-tabbar="false" @tap="handlePageTap">
		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-input-container" @tap.stop>
				<text class="iconfont icon-search"></text>
				<uni-easyinput 
					:inputBorder="false" 
					v-model="filterParams.keyword" 
					type="text" 
					class="search-input" 
					placeholder="请输入房屋名称/地区筛选" 
					@confirm="handleSearch"
					@focus="handleInputFocus"
					@clear="handleSearch"
				/>
				<text class="search-btn" @tap.stop="handleSearch">搜索</text>
			</view>
			
			<!-- 使用搜索历史记录组件 -->
			<search-history 
				:show="showHistorySearch" 
				:history="searchHistory"
				@select="selectHistoryItem"
				@clear="clearSearchHistory"
			/>
		</view>
		
		<!-- 状态栏 -->
		<view class="status-tabs">
			<view 
				class="status-tab" 
				:class="{ active: activeStatus === 'all' }"
				@click="changeStatus('all')"
			>
				全部资产
			</view>
			<view 
				class="status-tab" 
				:class="{ active: activeStatus === 'rented' }"
				@click="changeStatus('rented')"
			>
				已租赁
			</view>
			<view 
				class="status-tab" 
				:class="{ active: activeStatus === 'idle' }"
				@click="changeStatus('idle')"
			>
				闲置中
			</view>
		</view>
		
		<!-- 收藏列表 -->
		<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
			<view class="asset-list">
				<view 
					class="asset-item" 
					v-for="(item, index) in collectionList" 
					:key="index"
					@click="goToDetail(item)"
				>
					<view class="asset-img-container">
						<image class="asset-img" :src="getImageUrl(item.stateAsset?.imageUrl)" mode="aspectFill"></image>
						<view class="status-badge" :class="getStatusClass(item.stateAsset?.assetStatus || item.assetStatus)">{{getAssetStatusName(item.stateAsset?.assetStatus || item.assetStatus)}}</view>
					</view>
					<view class="asset-info">
						<view class="asset-name">{{item.stateAsset?.name || item.name || item.assetName}}</view>
						<view class="asset-area">{{item.stateAsset?.area || item.area || item.assetArea}}</view>
						<view class="asset-price-box">
							<view class="asset-price">
								<text v-if="shouldShowRentPrice(item)">出租价格:{{item.stateAsset?.rent || item.rent}}</text>
								<text v-if="shouldShowTransferPrice(item)" class="transfer-price">出售价格:{{item.stateAsset?.transferPrice || item.transferPrice}}</text>
							</view>
							<view class="asset-tag" :class="getTagClass(item.stateAsset?.type || item.type || item.assetType)">{{getTypeName(item.stateAsset?.type || item.type || item.assetType)}}</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-body>
	</my-page>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import MyPage from '@/components/MyPage.vue'
import MescrollBody from '@/uni_modules/mescroll-uni/components/mescroll-body/mescroll-body.vue'
import { getDictData } from '@/api/system'
import { getUserCollections } from '@/api/collection'
import SearchHistory from '@/components/SearchHistory.vue'
import useMescroll from "@/uni_modules/mescroll-uni/hooks/useMescroll.js"
import { onPageScroll, onReachBottom, onLoad } from '@dcloudio/uni-app'

const store = useStore()
const { mescrollInit, downCallback } = useMescroll(onPageScroll, onReachBottom) 

// 获取用户信息
const user = computed(() => {
	return store.state.user.user
})

// 筛选和状态相关
const activeStatus = ref('all')

// 字典数据
const typeFilterData = ref([])
const assetStatusData = ref([])

// 搜索历史相关
const showHistorySearch = ref(false)
const searchHistory = ref([])

// 获取搜索历史
const getSearchHistory = () => {
	try {
		const history = uni.getStorageSync('collectionSearchHistory')
		if (history) {
			searchHistory.value = JSON.parse(history)
		}
	} catch (e) {
		console.error('获取搜索历史失败', e)
		searchHistory.value = []
	}
}

// 保存搜索历史
const saveSearchHistory = (keyword) => {
	if (!keyword || keyword.trim() === '') return
	
	// 如果已存在相同关键词，先移除
	const index = searchHistory.value.findIndex(item => item === keyword)
	if (index !== -1) {
		searchHistory.value.splice(index, 1)
	}
	
	// 添加到历史记录的开头
	searchHistory.value.unshift(keyword)
	
	// 限制最多20条记录
	if (searchHistory.value.length > 20) {
		searchHistory.value = searchHistory.value.slice(0, 20)
	}
	
	// 保存到本地存储
	try {
		uni.setStorageSync('collectionSearchHistory', JSON.stringify(searchHistory.value))
	} catch (e) {
		console.error('保存搜索历史失败', e)
	}
}

// 清空搜索历史
const clearSearchHistory = () => {
	searchHistory.value = []
	try {
		uni.removeStorageSync('collectionSearchHistory')
		uni.showToast({
			title: '历史记录已清空',
			icon: 'none'
		})
	} catch (e) {
		console.error('清空搜索历史失败', e)
	}
}

// 选择历史记录项
const selectHistoryItem = (item) => {
	filterParams.keyword = item
	showHistorySearch.value = false
	handleSearch()
}

// 搜索栏点击
const handleSearch = () => {
	showHistorySearch.value = false
	if (filterParams.keyword && filterParams.keyword.trim() !== '') {
		saveSearchHistory(filterParams.keyword.trim())
	}
	refreshList()
}

// 处理输入框聚焦事件
const handleInputFocus = () => {
	showHistorySearch.value = true
}

// 添加一个监听页面点击的方法，关闭历史记录
const handlePageTap = () => {
	// 点击页面空白区域时，关闭历史记录
	if (showHistorySearch.value) {
		showHistorySearch.value = false
	}
}

// 初始化字典数据
const initDictData = async () => {
	try {
		// 获取资产类型字典
		const assetTypeRes = await getDictData('asset_type')
		if (assetTypeRes.code === 200 && assetTypeRes.data) {
			typeFilterData.value = assetTypeRes.data.map(item => ({
				label: item.dictLabel,
				value: item.dictValue
			}))
		}
		
		// 获取资产状态字典
		const assetStatusRes = await getDictData('asset_status')
		if (assetStatusRes.code === 200 && assetStatusRes.data) {
			assetStatusData.value = assetStatusRes.data.map(item => ({
				label: item.dictLabel,
				value: item.dictValue
			}))
		}
	} catch (error) {
		console.error('加载字典数据失败', error)
	}
}

// 更改资产状态
const changeStatus = (status) => {
	activeStatus.value = status
	
	// 根据状态设置查询参数
	if (status === 'all') {
		filterParams.assetStatus = null
	} else if (status === 'rented') {
		filterParams.assetStatus = 1
	} else if (status === 'idle') {
		filterParams.assetStatus = 0
	}
	
	refreshList()
}

// 获取资产类型名称
const getTypeName = (type) => {
	// 如果字典数据已加载
	if (typeFilterData.value && typeFilterData.value.length > 0) {
		const typeItem = typeFilterData.value.find(item => item.value == type)
		if (typeItem) return typeItem.label
	}
	
	// 默认类型映射
	const typeMap = {
		0: '商铺',
		1: '住宅',
		2: '办公室',
		3: '厂房',
		4: '仓库'
	}
	
	return typeMap[type] || '其他'
}

// 根据类型获取标签样式类
const getTagClass = (type) => {
	const tagClasses = {
		0: 'tag-shop',
		1: 'tag-house',
		2: 'tag-office',
		3: 'tag-factory',
		4: 'tag-warehouse'
	}
	return tagClasses[type] || 'tag-other'
}

// 根据状态值获取状态名称
const getAssetStatusName = (status) => {
	// 从字典数据中查找状态名称
	if (assetStatusData.value && assetStatusData.value.length > 0) {
		const statusItem = assetStatusData.value.find(item => item.value == status)
		if (statusItem) return statusItem.label
	}
	
	// 默认状态映射
	const statusMap = {
		0: '闲置中',
		1: '展示中',
		2: '已租赁'
	}
	
	return statusMap[status] || '未知状态'
}

// 根据状态值获取状态样式类
const getStatusClass = (status) => {
	const statusClasses = {
		0: 'status-idle',     // 闲置中
		1: 'status-display',  // 展示中
		2: 'status-rented'    // 已租赁
	}
	return statusClasses[status] || 'status-unknown'
}

// 处理图片URL
const getImageUrl = (imageUrl) => {
	// 处理null、undefined或空字符串的情况
	if (!imageUrl) return '/static/images/suoluetu.png'
	
	// 确保imageUrl是字符串类型
	if (typeof imageUrl !== 'string') {
		return '/static/images/suoluetu.png'
	}
	
	try {
		// 分割图片URL，取第一个
		const firstImage = imageUrl.split(',')[0]
		
		// 检查是否已包含http
		if (firstImage.startsWith('http')) {
			return firstImage
		}
		
		// 拼接基础URL
		return import.meta.env.VITE_APP_BASE_API + firstImage
	} catch (error) {
		console.error('处理图片URL出错:', error)
		return '/static/images/suoluetu.png'
	}
}

// 筛选参数
const filterParams = reactive({
	keyword: '',
	assetStatus: null
})

// 刷新列表
const refreshList = () => {
	// 重置列表为第一页，并重新加载数据
	if (mescrollRef.value) {
		mescrollRef.value.mescroll.resetUpScroll()
	}
}

// 收藏列表
const collectionList = ref([])

// mescroll实例对象
const mescrollRef = ref()

// 下拉刷新的配置
const downOption = {
	auto: false // 不自动加载
}

// 上拉加载的配置
const upOption = {
	use: true, // 是否启用上拉加载
	auto: true, // 是否在初始化完毕之后自动执行上拉加载的回调
	page: {
		num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
		size: 20 // 每页数据的数量
	},
	empty: {
		use: true, // 是否显示空布局
		tip: '暂无收藏资产' // 提示
	}
}

// 上拉加载的回调
const upCallback = (mescroll) => {
	// 获取收藏列表数据
	loadData((list) => {
		// 过滤和搜索数据
		let filteredList = filterData(list)
		
		// 如果是第一页需手动制空列表
		if (mescroll.num === 1) collectionList.value = []
		
		// 追加新数据
		collectionList.value = collectionList.value.concat(filteredList)
		
		// 结束加载
		mescroll.endSuccess(filteredList.length)
	})
}

// 过滤数据
const filterData = (list) => {
	if (!list || list.length === 0) return []
	
	return list.filter(item => {
		// 资产对象
		const asset = item
		
		// 关键词搜索
		if (filterParams.keyword && filterParams.keyword.trim() !== '') {
			const keyword = filterParams.keyword.toLowerCase()
			const name = (asset.name || asset.assetName || '').toLowerCase()
			const address = (asset.address || '').toLowerCase()
			
			if (!name.includes(keyword) && !address.includes(keyword)) {
				return false
			}
		}
		
		// 状态筛选
		if (filterParams.assetStatus !== null && asset.assetStatus != filterParams.assetStatus) {
			return false
		}
		
		return true
	})
}

// 加载收藏数据
const loadData = async (callback) => {
	try {
		uni.showLoading({
			title: '加载中...'
		})
		
		// 准备查询参数
		const queryParams = {}
		
		// 添加资产状态过滤条件
		if (filterParams.assetStatus !== null) {
			queryParams.assetStatus = filterParams.assetStatus
		}
		
		// 添加关键词搜索条件
		if (filterParams.keyword && filterParams.keyword.trim() !== '') {
			queryParams.keyword = filterParams.keyword.trim()
		}
		
		// 调用API接口获取数据
		const res = await getUserCollections(queryParams)
		
		uni.hideLoading()
		
		if (res.code === 200) {
			callback(res.rows || [])
		} else {
			uni.showToast({
				title: res.msg || '加载失败',
				icon: 'none'
			})
			callback([])
		}
	} catch (error) {
		uni.hideLoading()
		console.error('加载数据失败', error)
		uni.showToast({
			title: '网络异常，请稍后再试',
			icon: 'none'
		})
		callback([])
	}
}

// 跳转详情页
const goToDetail = (item) => {
	// 获取正确的资产ID
	const assetId = item.stateAsset?.id || item.assetId || item.id
	
	uni.navigateTo({
		url: `/pages/asset/detail?id=${assetId}`
	})
}

// 在页面初始化时调用
onMounted(() => {
	initDictData()
	getSearchHistory()
})

// 判断是否应该显示出租价格
const shouldShowRentPrice = (item) => {
	const method = item.stateAsset?.revitalizationMethod || item.revitalizationMethod
	const hasRentPrice = item.stateAsset?.rent || item.rent
	
	if (!hasRentPrice) return false
	
	return method === '出租' || method === '租售均可'|| method === '先租后让'
}

// 判断是否应该显示出售价格
const shouldShowTransferPrice = (item) => {
	const method = item.stateAsset?.revitalizationMethod || item.revitalizationMethod
	const hasTransferPrice = item.stateAsset?.transferPrice || item.transferPrice
	
	if (!hasTransferPrice) return false
	
	return method === '出售' || method === '租售均可'|| method === '先租后让'
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/index.scss';

::v-deep .my_page {
	.my_header {
		background: linear-gradient(to right, #2979ff, #1565C0);
		.wrap {
			background: linear-gradient(to right, #2979ff, #1565C0);
		}
	}
}

// 搜索框样式
.search-box {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20rpx 60rpx;
	background: linear-gradient(to right, #2979ff, #1565C0);
	position: relative;
	
	.search-input-container {
		flex: 1;
		width: 100%;
		height: 72rpx;
		background-color: #fff;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		
		.iconfont {
			color: #999;
			font-size: 32rpx;
			margin-right: 10rpx;
		}
		
		.search-input {
			flex: 1;
			height: 72rpx;
			font-size: 28rpx;
			color: #333;
		}
		
		.search-btn {
			margin-left: 20rpx;
			color: #fff;
			font-size: 30rpx;
			background: rgba(4, 96, 242, 1);
			width: 100rpx;
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 30rpx;
			text-align: center;
			margin-right: -20rpx;
		}
	}
}

// 状态标签样式
.status-tabs {
	display: flex;
	background-color: #f5f5f5;
	padding: 20rpx 30rpx;
	
	.status-tab {
		flex: 1;
		padding: 15rpx 30rpx;
		font-size: 28rpx;
		color: #333;
		text-align: center;
		margin-right: 20rpx;
		border-radius: 30rpx;
		background-color: #fff;
		
		&:last-child {
			margin-right: 0;
		}
		
		&.active {
			color: #fff;
			background-color: #2979ff;
			font-weight: normal;
		}
	}
}

// 资产列表样式
.asset-list {
	padding: 0 30rpx;
	
	.asset-item {
		display: flex;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		
		.asset-img-container {
			position: relative;
			width: 220rpx;
			height: 160rpx;
			margin: 20rpx;
			// 右上角状态标签
			.status-badge {
				position: absolute;
				top: 0;
				right: 0;
				padding: 4rpx 8rpx;
				border-radius: 8rpx;
				font-size: 26rpx;
				color: #fff;
				z-index: 10;
				
				&.status-idle {
					background-color: #f39c12; // 橙色 - 闲置中
				}
				
				&.status-display {
					background-color: #3498db; // 蓝色 - 展示中
				}
				
				&.status-rented {
					background-color: #27ae60; // 绿色 - 已租赁
				}
				
				&.status-unknown {
					background-color: #95a5a6; // 灰色 - 未知状态
				}
			}
		}
		
		.asset-img {
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
		}
		
		.asset-info {
			flex: 1;
			padding: 20rpx 20rpx 20rpx 0;
			
			.asset-name {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 10rpx;
				font-weight: bold;
			}
			
			.asset-area {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 20rpx;
			}
			
			.asset-price-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.asset-price {
					font-size: 28rpx;
					color: #ff5a5f;
					font-weight: bold;
					display: flex;
					flex-direction: column;
					
					.transfer-price {
						color: #ff9500;
						font-size: 24rpx;
						margin-top: 5rpx;
					}
				}
				
				.asset-tag {
					display: inline-block;
					padding: 4rpx 12rpx;
					font-size: 20rpx;
					border-radius: 4rpx;
					
					&.tag-shop {
						background-color: rgba(52, 195, 143, 0.1);
						color: #34c38f;
					}
					
					&.tag-house {
						background-color: rgba(241, 180, 76, 0.1);
						color: #f1b44c;
					}
					
					&.tag-office {
						background-color: rgba(80, 165, 241, 0.1);
						color: #50a5f1;
					}
					
					&.tag-factory {
						background-color: rgba(223, 71, 89, 0.1);
						color: #df4759;
					}
					
					&.tag-warehouse {
						background-color: rgba(102, 88, 221, 0.1);
						color: #6658dd;
					}
					
					&.tag-other {
					background-color: rgba(100, 100, 100, 0.1);
					color: #646464;
				}
			}
		}
	}
}
}
</style>

